package com.tanhua.server.service;

import com.tanhua.domain.mongo.Answer;
import com.tanhua.domain.mongo.SoulResult;
import com.tanhua.domain.vo.ReportVO;
import com.tanhua.domain.vo.SimilarUserVO;
import com.tanhua.domain.vo.SoulPaperVO;
import com.tanhua.dubbo.api.SoulPaperApi;
import com.tanhua.dubbo.api.SoulReportApi;
import com.tanhua.dubbo.api.SoulResultApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SoulService {

    @Reference
    private SoulPaperApi soulPaperApi;

    @Reference
    private SoulResultApi soulResultApi;

    @Reference
    private SoulReportApi soulReportApi;

    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 问卷列表
     * @return  问卷列表集合
     */
    public ResponseEntity soulPaperList( ) {
        Long userId = UserHolder.getUser().getId();
        //查询数据库中的问卷
        List<SoulPaperVO> soulPapers = soulPaperApi.findPaperList(userId);
        log.info("问卷：{}", soulPapers);
        return ResponseEntity.ok(soulPapers);
    }

    /**
     * 将用户提交的结果保存到用户的问卷测试结果中
     */
    public ResponseEntity saveAnswers(List<Answer> answers) {
        Long userId = UserHolder.getUser().getId();
        //先计算出分值
        //根据选项结果计算得分
        List<ObjectId> optionIds= new ArrayList<>();
        for (Answer answer : answers) {
            optionIds.add(new ObjectId(answer.getOptionId()));
        }
        //根据选项去计算总得分
        int score = soulResultApi.findScoreByOption(optionIds);

        //根据总分确定使用那一份报告
        SoulResult soulResult = new SoulResult(score);
        soulResult.setAnswers(answers);
        soulResult.setUserId(userId);
        String reportId = soulResultApi.saveAnswers(soulResult);
        return ResponseEntity.ok(reportId);
    }
    /**
     * 问卷报告
     * @param reportId   报告id
     * @return  报告信息
     */
    public ResponseEntity getReport(String reportId) {
        Long userId = UserHolder.getUser().getId();
        ReportVO reportVO = soulReportApi.findReport(reportId, userId);

        //对similarYou添加头像
        List<SimilarUserVO> users = reportVO.getSimilarYou();
        List<SimilarUserVO> similarYou = new ArrayList<>();
        if (users != null && users.size() > 0) {
            for (SimilarUserVO similarUserVO : users) {
                similarUserVO.setAvatar(userInfoApi.findById(similarUserVO.getId()).getAvatar());
                similarYou.add(similarUserVO);
            }
            reportVO.setSimilarYou(similarYou);
        }
        return ResponseEntity.ok(reportVO);
    }
}
